#include <Def.h>
#include <qfile.h>
#include <qtextcodec.h>
#include <qdatetime.h>
#include <qtextstream.h>
#include <qdebug.h>
#include "util.h"

QString readAllBufferFromFile(const QString& filename)
{
	QFile file(filename);
	if(!file.open(QIODevice::ReadOnly))
	{
		qDebug() << "call readAllBufferFromFile failed:" << filename;
		return QByteArray();
	}

	QTextCodec* codec = QTextCodec::codecForName("UTF8");
	QString content = codec->toUnicode(file.readAll());

	file.close();
	return content;
}

void saveToFile(const QString& filename,const QString& buffer)
{
	QFile file(filename);
	if(!file.open(QIODevice::WriteOnly))
	{
		qDebug() << "call saveToFile:" << filename << " failed";
		return;
	}

	file.write(buffer.toLocal8Bit());
	file.close();
}

void customMessageHandler(QtMsgType type,const QMessageLogContext& context,const QString& msg)
{
	QString txt;
	switch (type)
	{
	case QtDebugMsg:
		txt = QString("Debug: %1").arg(msg);
		break;
	case QtWarningMsg:
		txt = QString("Warning: %1").arg(msg);
		break;
	case QtCriticalMsg:
		txt = QString("Critical: %1").arg(msg);
		break;
	case QtFatalMsg:
		txt = QString("Fatal: %1").arg(msg);
		abort();
	default:
		break;
	}

	QString date = QDate::currentDate().toString("yyyy-MM-dd");
	QString time = QTime::currentTime().toString();
	txt = date + " " + time + " " + txt;

	QString fileName = QString("..\\log\\report-%1.log").arg(date);
	QFile outFile(fileName);
	outFile.open(QIODevice::WriteOnly | QIODevice::Append);
	QTextStream ts(&outFile);
	ts << txt << endl;
}
